﻿using AutoMapper;
using Basic.Traceability.Domain.DeepProcessing;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.DeepProcessing.DeepProcessingAuxiliaryMaterials;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.DeepProcessing.DeepProcessingAuxiliaryMaterials
{
    public class CreateDeepProcessingAuxiliaryMaterialsHandler : IRequestHandler<CreateDeepProcessingAuxiliaryMaterialsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingAuxiliaryMaterialsModel> materislsRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateDeepProcessingAuxiliaryMaterialsHandler> logger;

        public CreateDeepProcessingAuxiliaryMaterialsHandler(IBaseRepository<DeepProcessingAuxiliaryMaterialsModel> materislsRepository, IMapper mapper, ILogger<CreateDeepProcessingAuxiliaryMaterialsHandler> logger)
        {
            this.materislsRepository = materislsRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加深加工辅料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateDeepProcessingAuxiliaryMaterialsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<DeepProcessingAuxiliaryMaterialsModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = materislsRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加深加工辅料信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                logger.LogInformation("添加深加工辅料信息成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "添加深加工辅料信息失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                logger.LogError("添加深加工辅料信息失败");
                return Task.FromResult(res);
            }
            
        }
    }
}
